<template>
  <div class="page">
    <h2>每日一言</h2>
    <p v-if="loading">加载中...</p>
    <p v-else v-html="qinghua"></p>
    <button @click="fetchQinghua(true)">换一句</button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const qinghua = ref('')
const loading = ref(true)

const CACHE_KEY = 'yiyan_cache'
const CACHE_DURATION = 60 * 1000 // 1分钟

function getCache() {
  const cache = localStorage.getItem(CACHE_KEY)
  if (!cache) return null
  try {
    const { value, time } = JSON.parse(cache)
    if (Date.now() - time < CACHE_DURATION) {
      return value
    }
  } catch (e) {}
  return null
}

function setCache(value) {
  localStorage.setItem(CACHE_KEY, JSON.stringify({ value, time: Date.now() }))
}

async function fetchQinghua(skipCache = false) {
  // skipCache=true 时跳过缓存
  if (!skipCache) {
    const cached = getCache()
    if (cached) {
      qinghua.value = cached
      loading.value = false
      return
    }
  }
  loading.value = true
  try {
    // 只用主API+最快代理
    const apiUrl = 'https://api.zxki.cn/api/twqh'
    const proxy = 'https://api.allorigins.win/raw?url='
    const url = proxy + encodeURIComponent(apiUrl + '?t=' + Date.now())
    const res = await fetch(url, { method: 'GET' })
    if (res.ok) {
      const data = await res.text()
      if (data && data.trim()) {
        qinghua.value = data.trim().replace(/\\n|\r\n|\n|\r/g, '<br>')
        setCache(qinghua.value)
        loading.value = false
        return
      }
    }
    qinghua.value = '今天也要开开心心的哦~'
  } catch (e) {
    qinghua.value = '获取失败，请重试'
  } finally {
    loading.value = false
  }
}

onMounted(() => fetchQinghua(false))
</script>

<style scoped>
.page {
  text-align: center;
  margin-top: 60px;
}
button {
  margin-top: 20px;
  padding: 8px 24px;
  background: #42b983;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  cursor: pointer;
  transition: background 0.2s;
}
button:hover {
  background: #369870;
}
</style> 